package com.openapi.protocol.decode.subPackageHandle.hj212Stream;

import exsun.jt808.data.util.executorsThread.ScheduledHandle;
import exsun.jt808.data.parseUtil.Jsalt12Alarm;
import exsun.jt808.data.upload_data.jsatl12.AttachmentFileInfo;
import exsun.jt808.data.upload_data.jsatl12.FileInfo;
import exsun.jt808.data.util.parse.HexStrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 文件信息缓存
 */
@Component
public class FileInfoCache {
    private static final int expiredTime = 600000;//60s
    private final Logger logger = LoggerFactory.getLogger(FileInfoCache.class);

    private void FileInfoCache(){
        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    //判断是否有过期的文件信息及文件数据缓存，清理
                    List<String> expiredFiles = FileInfoCache.getExpiredFiles();
                    FileInfoCache.removeFileInfo(expiredFiles);
                    FileBitStreamCache.removeStream(expiredFiles);
                    logger.info("清除报警资源缓存：文件目录消息剩余{}条，文件数据剩余{}条",
                            getFileSize(),FileBitStreamCache.getFileSize());
                }catch (Exception e){
                    logger.error("SubpackageHandle AutoRemoveExprie:" + e.getMessage());
                }
            }
        };
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        ScheduledHandle.getInst().getService().scheduleAtFixedRate(runnable, 0, 60, TimeUnit.SECONDS);
    }
    /**
     * key:文件名
     */
    private static Map<String, FileInfo> fileInfos = new HashMap<String, FileInfo>();

    /**
     * 更新文件信息
     * @param attachmentFileInfos 文件信息
     * @param alarmCode 报警标志号
     * @param alarmFlage 报警编号
     */
    public static void updateFileInfo(String phoneNum, List<AttachmentFileInfo> attachmentFileInfos, String alarmCode, String alarmFlage){
        for(AttachmentFileInfo attachmentFileInfo: attachmentFileInfos){
            FileInfo fileInfo = new FileInfo();
            fileInfo.setPhoneNum(phoneNum);
            fileInfo.setFileName(attachmentFileInfo.getFileName());
            fileInfo.setFileSize(attachmentFileInfo.getFileSize());
            fileInfo.setAlarmCode(alarmCode);
            fileInfo.setDate(alarmFlage.substring(14,26));
            String[] infos = attachmentFileInfo.getFileName().split("_");
            if(infos.length >= 4){
                fileInfo.setFileType(Integer.parseInt(infos[0]));
                fileInfo.setChannel(Integer.parseInt(infos[1]));

//                int type1 = Integer.parseInt(infos[2].substring(0,2));
//                int type2 = Integer.parseInt(infos[2].substring(2,4));
                int type1 = HexStrUtil.HexToInt(infos[2].substring(0,2));
                int type2 = HexStrUtil.HexToInt(infos[2].substring(2,4));
                int alarmType = Jsalt12Alarm.getAlarmType(type1, type2);
                fileInfo.setAlarmType(alarmType);
                fileInfo.setSeriNo(Integer.parseInt(infos[3]));
            }
            fileInfo.setUpdateDate(new Date());
            fileInfos.put(attachmentFileInfo.getFileName(), fileInfo);
        }
    }

    public static void updateFileInfo(String phoneNum, String fileName, int fileSize){
        FileInfo fileInfo = new FileInfo();
        fileInfo.setPhoneNum(phoneNum);
        fileInfo.setFileName(fileName);
        fileInfo.setFileSize(fileSize);
        //无报警编号和日期
        String[] infos = fileName.split("_");
        if(infos.length == 2){
            fileInfo.setFileType(Integer.parseInt(infos[0]));
            fileInfo.setChannel(Integer.parseInt(infos[1]));
        }
        fileInfo.setUpdateDate(new Date());
        fileInfos.put(fileName, fileInfo);
    }

    public static FileInfo getFileInfo(String fileName){
        if(!fileInfos.containsKey(fileName))return null;
        return fileInfos.get(fileName);
    }

    public static List<String> getExpiredFiles(){
        List<String> expiredInfos = new ArrayList<String>();
        for(FileInfo info: fileInfos.values()){
            //获取10分钟前的数据
            if(info.getUpdateDate().getTime() < new Date().getTime() - expiredTime){
                expiredInfos.add(info.getFileName());
            }
        }
        return expiredInfos;
    }

    public static void removeFileInfo(List<String> fileNames){
        for(String fileName: fileNames){
            removeFileInfo(fileName);
        }
    }

    public static void removeFileInfo(String fileName){
        if(fileInfos.containsKey(fileName)){
            fileInfos.remove(fileName);
        }
    }

    public static int getFileSize(){
        return fileInfos.size();
    }

}
